<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="provider" label="支付供应商">
        <uni-data-checkbox v-model="formData.provider" :localdata="formOptions.provider_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="pay_status" label="订单状态">
        <uni-data-checkbox v-model="formData.pay_status" :localdata="formOptions.pay_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="group_buying_price" label="团派优惠金额">
        <uni-easyinput type="number" v-model="formData.group_buying_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="refund_total_price" label="已退款总额度">
        <uni-easyinput type="number" v-model="formData.refund_total_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="订单状态">
        <undefined v-model="formData.status"></undefined>
      </uni-forms-item>
      <uni-forms-item name="rate" label="">
        <uni-data-checkbox v-model="formData.rate" :localdata="formOptions.rate_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="pay_type" label="订单支付类型">
        <uni-easyinput placeholder="订单类型 goods：订单付款 recharge：余额充值付款 vip：vip充值付款 等等，可自定义" v-model="formData.pay_type" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="service_type" label="配送类型，外卖配送或到店就餐">
        <uni-easyinput v-model="formData.service_type"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="service_time" label="预计送达时间">
        <undefined v-model="formData.service_time"></undefined>
      </uni-forms-item>
      <uni-forms-item name="reality_service_time" label="实际送达时间">
        <undefined v-model="formData.reality_service_time"></undefined>
      </uni-forms-item>
      <uni-forms-item name="serial_number" label="今日订单编号">
        <uni-easyinput type="number" v-model="formData.serial_number"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cancel_order" label="是否已申请取消订单">
        <undefined v-model="formData.cancel_order"></undefined>
      </uni-forms-item>
      <uni-forms-item name="rider" label="骑手信息">
        <undefined v-model="formData.rider"></undefined>
      </uni-forms-item>
      <uni-forms-item name="type" label="订单类型">
        <uni-easyinput placeholder="订单类型 1：外卖 2：到店就餐" type="number" v-model="formData.type"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="reminder" label="是否已催单">
        <undefined v-model="formData.reminder"></undefined>
      </uni-forms-item>
      <uni-forms-item name="order_no" label="业务系统订单号">
        <uni-easyinput placeholder="业务系统订单号，控制在20-28位（不可以是24位,24位在阿里云空间可能会有问题，可重复，代表1个业务订单会有多次付款的情况）" v-model="formData.order_no" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="out_trade_no" label="支付插件订单号">
        <uni-easyinput placeholder="支付插件订单号（需控制唯一，不传则由插件自动生成）" v-model="formData.out_trade_no" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="distance" label="商家到买家的距离">
        <uni-easyinput type="number" v-model="formData.distance"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="delivery_time" label="配送时间">
        <uni-easyinput placeholder="以分钟计算" type="number" v-model="formData.delivery_time"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="delivery_price" label="收取客户的配送费">
        <uni-easyinput placeholder="商家收取客户的配送费，以分为单位" type="number" v-model="formData.delivery_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="reality_delivery_time" label="实际配送时间">
        <uni-easyinput placeholder="订单完成后再更新到此字段，以分钟计算" type="number" v-model="formData.reality_delivery_time"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="timeOut" label="是否超时">
        <undefined v-model="formData.timeOut"></undefined>
      </uni-forms-item>
      <uni-forms-item name="deduct_delivery_price" label="平台扣除配送费">
        <uni-easyinput type="number" v-model="formData.deduct_delivery_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="total_price" label="商品总金额">
        <uni-easyinput placeholder="商品总金额，不包括配送费和打包费" type="number" v-model="formData.total_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="total_number" label="购买商品的总数量">
        <uni-easyinput type="number" v-model="formData.total_number"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="pack_price" label="打包费">
        <uni-easyinput type="number" v-model="formData.pack_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="preferential" label="平台减免金额">
        <uni-easyinput type="number" v-model="formData.preferential"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="platform_commission" label="平台佣金">
        <uni-easyinput type="number" v-model="formData.platform_commission"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="advance_income_price" label="预计收入金额">
        <uni-easyinput type="number" v-model="formData.advance_income_price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="user_id" label="用户ID">
        <uni-easyinput placeholder="用户id，参考uni-id-users表" v-model="formData.user_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="nickname" label="用户昵称">
        <uni-easyinput placeholder="用户昵称冗余" v-model="formData.nickname" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="notes" label="备注">
        <uni-easyinput v-model="formData.notes"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="tableware" label="是否需要餐具说明">
        <uni-easyinput v-model="formData.tableware"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="tableware_number" label="餐具数量">
        <uni-easyinput type="number" v-model="formData.tableware_number"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="address" label="收货人信息">
        <undefined v-model="formData.address"></undefined>
      </uni-forms-item>
      <uni-forms-item name="shop_id" label="店铺id，关联shop表">
        <uni-easyinput v-model="formData.shop_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="shop_user_id" label="店铺对应的user_id，关联shop表">
        <uni-easyinput v-model="formData.shop_user_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="goods" label="购买的商品列表">
        <uni-data-checkbox :multiple="true" v-model="formData.goods"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="client_ip" label="客户端IP">
        <uni-easyinput placeholder="创建支付的客户端ip" v-model="formData.client_ip" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="openid" label="openid">
        <uni-easyinput placeholder="发起支付的用户openid" v-model="formData.openid" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="支付描述">
        <uni-easyinput placeholder="支付描述，如：uniCloud个人版包月套餐" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="err_msg" label="支付失败原因">
        <uni-easyinput placeholder="支付失败原因" v-model="formData.err_msg" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="total_fee" label="订单总金额">
        <uni-easyinput placeholder="支付订单总金额，单位为分，100等于1元" type="number" v-model="formData.total_fee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="refund_fee" label="订单总退款金额">
        <uni-easyinput placeholder="订单总退款金额，单位为分，100等于1元" type="number" v-model="formData.refund_fee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="refund_count" label="当前退款笔数">
        <uni-easyinput placeholder="当前退款笔数 (退款单号为 out_trade_no-refund_count)" type="number" v-model="formData.refund_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="refund_list" label="退款详情">
        <uni-data-checkbox :multiple="true" v-model="formData.refund_list"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="is_receive_order" label="是否接单，默认为true">
        <switch @change="binddata('is_receive_order', $event.detail.value)" :checked="formData.is_receive_order"></switch>
      </uni-forms-item>
      <uni-forms-item name="provider_appid" label="开放平台appid">
        <uni-easyinput placeholder="公众号appid，小程序appid，app开放平台appid 等" v-model="formData.provider_appid" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="appid" label="DCloud AppId">
        <uni-easyinput placeholder="dcloud_appid" v-model="formData.appid" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="user_order_success" label="回调状态">
        <switch @change="binddata('user_order_success', $event.detail.value)" :checked="formData.user_order_success"></switch>
      </uni-forms-item>
      <uni-forms-item name="custom" label="自定义数据">
        <undefined v-model="formData.custom"></undefined>
      </uni-forms-item>
      <uni-forms-item name="original_data" label="异步通知原始数据">
        <undefined v-model="formData.original_data"></undefined>
      </uni-forms-item>
      <uni-forms-item name="create_date" label="下单时间">
        <undefined v-model="formData.create_date"></undefined>
      </uni-forms-item>
      <uni-forms-item name="pay_date" label="支付时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.pay_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="notify_date" label="异步通知时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.notify_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="cancel_date" label="取消时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.cancel_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="is_comment" label="是否已平价">
        <switch @change="binddata('is_comment', $event.detail.value)" :checked="formData.is_comment"></switch>
      </uni-forms-item>
      <uni-forms-item name="stat_data" label="uni统计相关数据">
        <undefined v-model="formData.stat_data"></undefined>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '@/js_sdk/validator/orders.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'orders';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "provider": "",
        "pay_status": 1,
        "group_buying_price": 0,
        "refund_total_price": 0,
        "status": null,
        "rate": null,
        "pay_type": "",
        "service_type": "",
        "service_time": null,
        "reality_service_time": null,
        "serial_number": null,
        "cancel_order": null,
        "rider": null,
        "type": 1,
        "reminder": null,
        "order_no": "",
        "out_trade_no": "",
        "distance": null,
        "delivery_time": null,
        "delivery_price": 0,
        "reality_delivery_time": null,
        "timeOut": null,
        "deduct_delivery_price": 0,
        "total_price": 0,
        "total_number": 0,
        "pack_price": 0,
        "preferential": null,
        "platform_commission": 0,
        "advance_income_price": 0,
        "user_id": "",
        "nickname": "",
        "notes": "",
        "tableware": "",
        "tableware_number": null,
        "address": null,
        "shop_id": "",
        "shop_user_id": "",
        "goods": [],
        "client_ip": "",
        "openid": "",
        "description": "",
        "err_msg": "",
        "total_fee": null,
        "refund_fee": null,
        "refund_count": null,
        "refund_list": [],
        "is_receive_order": true,
        "provider_appid": "",
        "appid": "",
        "user_order_success": null,
        "custom": null,
        "original_data": null,
        "create_date": null,
        "pay_date": null,
        "notify_date": null,
        "cancel_date": null,
        "is_comment": false,
        "stat_data": null
      }
      return {
        formData,
        formOptions: {
          "provider_localdata": [
            {
              "text": "微信支付",
              "value": "wxpay"
            },
            {
              "text": "支付宝",
              "value": "alipay"
            },
            {
              "text": "苹果应用内支付",
              "value": "appleiap"
            }
          ],
          "pay_status_localdata": [
            {
              "text": "未支付",
              "value": 0
            },
            {
              "text": "已支付",
              "value": 1
            },
            {
              "text": "已部分退款",
              "value": 2
            },
            {
              "text": "已全额退款",
              "value": 3
            }
          ],
          "rate_localdata": [
            {
              "text": "好评",
              "value": 1
            },
            {
              "text": "中评",
              "value": 2
            },
            {
              "text": "差评",
              "value": 3
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("provider,pay_status,group_buying_price,refund_total_price,status,rate,pay_type,service_type,service_time,reality_service_time,serial_number,cancel_order,rider,type,reminder,order_no,out_trade_no,distance,delivery_time,delivery_price,reality_delivery_time,timeOut,deduct_delivery_price,total_price,total_number,pack_price,preferential,platform_commission,advance_income_price,user_id,nickname,notes,tableware,tableware_number,address,shop_id,shop_user_id,goods,client_ip,openid,description,err_msg,total_fee,refund_fee,refund_count,refund_list,is_receive_order,provider_appid,appid,user_order_success,custom,original_data,create_date,pay_date,notify_date,cancel_date,is_comment,stat_data").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
